package P067_ListTraversalMethod;

import org.junit.Test;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.RandomAccess;

/**
 * 不同的列表选择不同的遍历方法
 */
public class ListTraversalMethod {

    @Test
    public void Test1() {
        //学生数量
        int stuNum = 2000 * 10000;
        //每个学生的分数
        ArrayList<Integer> scores = new ArrayList<>(stuNum);
        for (int i = 0; i < stuNum; i++) {
            scores.add(new Random().nextInt(150));
        }
        long start = System.currentTimeMillis();
        System.out.println("平均分:" + average(scores));
        System.out.println("用时:" + (System.currentTimeMillis() - start) + "ms");
    }

    //foreach遍历
    public static int avgForeach(List<Integer> scores) {
        int sum = 0;
        for (Integer score : scores) {
            sum += score;
        }
        return sum / scores.size();
    }

    //下标遍历
    public static int avgIndex(List<Integer> scores) {
        int sum = 0;
        for (int i = 0; i < scores.size(); i++) {
            sum += scores.get(i);
        }
        return sum / scores.size();
    }

    public static int average(List<Integer> scores) {
        int sum = 0;
        if (scores instanceof RandomAccess) {
            for (int i = 0; i < scores.size(); i++) {
                sum += scores.get(i);
            }
        } else {
            for (Integer score : scores) {
                sum += score;
            }
        }
        return sum / scores.size();
    }
}
